<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/1/4 0004
 * Time: 9:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\business;

use app\common\model\MallOrderGoods as ModelObj;
use app\common\validate\OrderGoods as ValObj;
use think\Exception;

class OrderGoods extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * 查询订单信息
     * @param {Object} $ordersn
     */
    public function getByOrderId($ordersn)
    {
        $where = [['ordersn', '=', $ordersn]];
        try {
            $result = $this->modelObj->getModelByInfo($where, '*');
        } catch (\Exception $e) {
            throw new Exception("系统内部错误");
        }
        return $result;
    }


    /**
     * 获取订单商品记录
     * @param $order_id
     * @return array
     * @throws Exception
     */
    public function getByOrderGoodsList($order_id){

        try {
            $result =$this->modelObj->alias('og')
                ->field('og.goods_id,og.goods_name,og.total,og.price,g.logo,g.title_desc,g.sales,g.virtual_sales,g.stock')
                ->join('mall_goods g','og.goods_id=g.id')
                ->where("og.order_id='".$order_id."'")
                ->order('og.create_time desc')
                ->select()
                ->toArray();

        } catch (\Exception $e) {
            throw new Exception("系统内部错误");
        }
        return $result;
    }


    /**
     * 下单商品订单表
     * @param $data
     * @return void
     * @throws Exception
     */
    public function saveData($data)
    {
        try {
            $orderinfo = $this->modelObj->getByOrderId($data['id']);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("系统内部错误");
        }
        if ($orderinfo) {
            $result = $orderinfo->save($data);
        } else {
            $result = $this->modelObj->save($data);
        }
        return $result;
    }

    /**
     * 批量写入订单商品表
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function insertDatas($data)
    {
        try {
            $this->modelObj->insertAll($data);
        } catch (\Exception $e) {
            throw new Exception("系统内部错误");
        }
        return true;
    }


}